//
//  YZXDaysMenuView.m
//  YZXCalendar
//
//  Created by 尹星 on 2017/6/27.
//  Copyright © 2017年 尹星. All rights reserved.
//

#import "YZXDaysMenuView.h"
#import "YZXCalendarCollectionViewCell.h"
#import "YZXPlainFlowLayout.h"
#import "YZXCalendarModel.h"
#import "YZXCalendarCollectionViewHeaderView.h"
#import "UIColor+Hexadecimal.h"
#import "YZXCalendarHelper.h"

#define collectionView_width (self.bounds.size.width)

#define dayView_width (collectionView_width / 7.f)

static const CGFloat collectionView_headerHeight = 44.0;

@interface YZXDaysMenuView ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView                          *collectionView;
//collectionView数据
@property (nonatomic, copy) NSArray <YZXCalendarModel *>                *collectionViewData;
//manager
@property (nonatomic, strong) YZXCalendarHelper                         *calendarHelper;
//数据
@property (nonatomic, strong) YZXCalendarModel                          *model;
//用于记录点击的cell
@property (nonatomic, strong) NSMutableArray <NSIndexPath *>            *selectedArray;

@end

static NSString *collectionViewCellIdentify = @"calendarCell";
static NSString *collectionViewHeaderIdentify = @"calendarHeader";

@implementation YZXDaysMenuView {
    NSString *_startDateString;
    NSString *_endDateString;
}

- (instancetype)initWithFrame:(CGRect)frame withStartDateString:(NSString *)startDateString endDateString:(NSString *)endDateString
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        _startDateString = startDateString;
        _endDateString = endDateString;
        [self p_initData];
        [self p_initView];
    }
    return self;
}

- (void)p_initData
{
    self.calendarHelper = YZXCalendarHelper.helper;
    
    self.model = [[YZXCalendarModel alloc] init];
    
    self.selectedArray = [NSMutableArray array];
    
    NSDateFormatter *formatter = [[YZXCalendarHelper helper] yearMonthAndDayFormatter];
    NSDate *startDate = [formatter dateFromString:_startDateString];
    NSDate *endDate = [formatter dateFromString:_endDateString];
    
    self.collectionViewData = [self.model achieveCalendarModelWithData:startDate toDate:endDate];
}

- (void)p_initView
{
    [self.collectionView registerNib:[UINib nibWithNibName:@"YZXCalendarCollectionViewHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:collectionViewHeaderIdentify];
//    [self.collectionView registerNib:[UINib nibWithNibName:@"YZXCalendarCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:collectionViewCellIdentify];
    [self.collectionView registerClass:[YZXCalendarCollectionViewCell class] forCellWithReuseIdentifier:collectionViewCellIdentify];
    [self addSubview:self.collectionView];
    NSString *now = [[YZXCalendarHelper helper].yearMonthAndDayFormatter stringFromDate:[NSDate date]];
    for (YZXCalendarModel *model in self.collectionViewData) {
        for (YZXCalendarDayModel *dayModel in model.dayArray) {
            if ([dayModel.dmy isEqualToString:now]) {
                [_collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:dayModel.item inSection:dayModel.section] animated:YES scrollPosition:UICollectionViewScrollPositionBottom];
                break;
            }
        }
    }
}

#pragma mark - <UICollectionViewDelegate,UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.collectionViewData.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    YZXCalendarModel *model = self.collectionViewData[section];
    return model.dayArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YZXCalendarCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionViewCellIdentify forIndexPath:indexPath];
    [cell layoutContentViewOfCollectionViewCellWithCellIndxePath:indexPath
                                                           model:self.collectionViewData[indexPath.section]];
    
    if (self.selectedArray.count == 2 && [indexPath compare:self.selectedArray.firstObject] == NSOrderedDescending && [indexPath compare:self.selectedArray.lastObject] == NSOrderedAscending) {
//        [cell changeContentViewBackgroundColor:[UIColor colorWithRed:221/255.0 green:81/255.0 blue:77/255.0 alpha:0.45]];
//        [cell changeDayTextColor:[UIColor whiteColor]];
        [cell showInstructionsView];
    }
    
    //将选中的按钮改变样式
    [self.selectedArray enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.section == indexPath.section && obj.item == indexPath.item) {
            [self setSelectCellStyle:cell];
            if (self.selectedArray.count == 2) {
                if (idx == 0) {
                    [cell showBottomInstructionsViewMasksToLeft];
                } else {
                    [cell showBottomInstructionsViewMasksToRight];
                }
                
            }
        }
    }];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //自定义选择
    switch (self.selectedArray.count) {
        case 0://选择第一个时间
        {
            //设置点击的cell的样式
            [self p_changeTheSelectedCellStyleWithIndexPath:indexPath];
            //记录当前点击的cell
            [self.selectedArray addObject:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]];
            
            if (_delegate && [_delegate respondsToSelector:@selector(clickCalendarWithStartDate:andEndDate:)]) {
                YZXCalendarModel *model =  self.collectionViewData[indexPath.section];
                YZXCalendarDayModel *dayModel = model.dayArray[indexPath.item];
                NSString *startString = dayModel.dmy;
                [_delegate clickCalendarWithStartDate:startString andEndDate:nil];
            }
        }
            break;
        case 1://选择第二个时间
        {
            //如果第二次的选择和第一次的选择一样，则表示取消选择
            if (self.selectedArray.firstObject.section == indexPath.section && self.selectedArray.firstObject.item == indexPath.item) {
                [self p_recoveryIsNotSelectedWithIndexPath:self.selectedArray.firstObject];
                [self.selectedArray removeAllObjects];
                if (_delegate && [_delegate respondsToSelector:@selector(clickCalendarWithStartDate:andEndDate:)]) {
                    [_delegate clickCalendarWithStartDate:nil andEndDate:nil];
                }
                return;
            }
            
            
            YZXCalendarModel *model1 =  self.collectionViewData[self.selectedArray.firstObject.section];
            YZXCalendarDayModel *dayModel1 = model1.dayArray[self.selectedArray.firstObject.item];
            NSString *startDate = dayModel1.dmy;
            
            YZXCalendarModel *model2 =  self.collectionViewData[indexPath.section];
            YZXCalendarDayModel *dayModel2 = model2.dayArray[indexPath.item];
            NSString *endDate = dayModel2.dmy;
            
            YZXCalendarHelper *helper = [YZXCalendarHelper helper];
            NSDateComponents *components = [helper.calendar components:NSCalendarUnitDay fromDate:[helper.yearMonthAndDayFormatter dateFromString:startDate] toDate:[helper.yearMonthAndDayFormatter dateFromString:endDate] options:0];
            //当设置了maxChooseNumber时判断选择的时间段是否超出范围
            if (self.maxChooseNumber) {
                if (labs(components.day) > self.maxChooseNumber - 1) {
                    if (_delegate && [_delegate respondsToSelector:@selector(clickCalendarWithStartDate:andEndDate:)]) {
                        [_delegate clickCalendarWithStartDate:startDate andEndDate:@"error"];
                    }
                    return;
                }
            }
            
            //记录当前点击的cell
            [self.selectedArray addObject:[NSIndexPath indexPathForRow:indexPath.item inSection:indexPath.section]];
            
            //对selectedArray进行排序，小的在前，大的在后
            [self p_sortingTheSelectedArray];
            //排序之后重新确定开始和结束时间
            YZXCalendarModel *startModel =  self.collectionViewData[self.selectedArray.firstObject.section];
            YZXCalendarDayModel *startDayModel = startModel.dayArray[self.selectedArray.firstObject.item];
            startDate = startDayModel.dmy;
            
            YZXCalendarModel *endModel =  self.collectionViewData[self.selectedArray.lastObject.section];
            YZXCalendarDayModel *endDayModel = endModel.dayArray[self.selectedArray.lastObject.item];
            endDate = endDayModel.dmy;
            
            //时间选择完毕，刷新界面
            [self.collectionView reloadData];
            //代理返回数据
            if (_delegate && [_delegate respondsToSelector:@selector(clickCalendarWithStartDate:andEndDate:)]) {
                [_delegate clickCalendarWithStartDate:startDate andEndDate:endDate];
            }
        }
            break;
        case 2://重新选择
        {
            //重新选择时，将之前点击的cell恢复成为点击状态，并移除数组中所有对象
            [self.selectedArray removeAllObjects];
            //记录当前点击的cell
            [self.selectedArray addObject:indexPath];
            [self.collectionView reloadData];
            //
            if (_delegate && [_delegate respondsToSelector:@selector(clickCalendarWithStartDate:andEndDate:)]) {
                YZXCalendarModel *startModel =  self.collectionViewData[self.selectedArray.firstObject.section];
                YZXCalendarDayModel *startDayModel = startModel.dayArray[self.selectedArray.firstObject.item];
                NSString *startString = startDayModel.dmy;
                [_delegate clickCalendarWithStartDate:startString andEndDate:nil];
            }
        }
            break;
        default:
            break;
    }
    
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        YZXCalendarCollectionViewHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:collectionViewHeaderIdentify forIndexPath:indexPath];
        //获取英文月份
        NSDate * date = [[YZXCalendarHelper.helper yearAndMonthFormatter] dateFromString:self.collectionViewData[indexPath.section].headerTitle];
        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"MMMM yyyy"];
        NSString * time_now = [formatter stringFromDate:date];
        headerView.textLabel.text = time_now;
        return headerView;
    }
    return [[UICollectionReusableView alloc] init];
}

/** collection头部的大小*/
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return  CGSizeMake(collectionView.bounds.size.width, 44);
}

/** collection尾部的大小*/
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeZero;
}

//对选中的selectedArray中的数据排序
- (void)p_sortingTheSelectedArray
{
    if ([self.selectedArray.firstObject compare:self.selectedArray.lastObject] == NSOrderedDescending) {
        self.selectedArray = [[[[self.selectedArray copy] reverseObjectEnumerator] allObjects] mutableCopy];
    }
}

//改变cell的样式为选中
- (void)p_changeTheSelectedCellStyleWithIndexPath:(NSIndexPath *)indexPath
{
    YZXCalendarCollectionViewCell *cell = (YZXCalendarCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    [self setSelectCellStyle:cell];
}

- (void)setSelectCellStyle:(YZXCalendarCollectionViewCell *)cell {
    [cell changeContentViewBackgroundColor:[UIColor colorWithRed:86/255.0 green:118/255.0 blue:144/255.0 alpha:1.0]];
    [cell changeDayTextColor:[UIColor whiteColor]];
    [cell masksToBoundsCornerRadius];
}

//恢复成为未选中状态
- (void)p_recoveryIsNotSelectedWithIndexPath:(NSIndexPath *)indexPath
{
    //回复之前选择的cell样式
    YZXCalendarCollectionViewCell *selectedCell = (YZXCalendarCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    [selectedCell changeContentViewBackgroundColor:[UIColor whiteColor]];
    
    //判断之前点击的是否为周末和当天
    if ([self p_judgepWeekendAndToday:indexPath]) {
        [selectedCell changeDayTextColor:[UIColor redColor]];
    }else {
        [selectedCell changeDayTextColor:[UIColor blackColor]];
    }
}

//判断是否为周末和当天
- (BOOL)p_judgepWeekendAndToday:(NSIndexPath *)indexPath
{
    BOOL todayFlag = ([YZXCalendarHelper.helper determineWhetherForTodayWithIndexPaht:indexPath model:self.collectionViewData[indexPath.section]] == YZXDateEqualToToday);
    BOOL isOverTheWeekend = self.collectionViewData[indexPath.section].dayArray[indexPath.row].isOverTheWeekend;
    return isOverTheWeekend || todayFlag;
}

#pragma mark - 懒加载
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        YZXPlainFlowLayout *layout = [[YZXPlainFlowLayout alloc] init];
        //        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(floor(dayView_width), floor(dayView_width));
        layout.headerReferenceSize = CGSizeMake(collectionView_width, collectionView_headerHeight);
        CGFloat tempW = collectionView_width - (floor(dayView_width) * 7);
        layout.sectionInset = UIEdgeInsetsMake(0, tempW *0.5, 0, tempW *0.5);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.naviHeight = collectionView_headerHeight;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, collectionView_width, self.bounds.size.height) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
    };
    return _collectionView;
}


- (void)setDateArray:(NSArray *)dateArray
{
    _dateArray = dateArray;
    if (!_dateArray) {
        return;
    }
    //传入两个时间时，查找其indexPath信息，用在collectionView上展现
    for (YZXCalendarModel * model in self.collectionViewData) {
        for (YZXCalendarDayModel *dayModel in model.dayArray) {
            if ([dayModel.dmy isEqualToString:_dateArray.firstObject]) {
                [self.selectedArray addObject:[NSIndexPath indexPathForItem:dayModel.item inSection:dayModel.section]];
            }
            if ([dayModel.dmy isEqualToString:_dateArray.lastObject]) {
                [self.selectedArray addObject:[NSIndexPath indexPathForItem:dayModel.item inSection:dayModel.section]];
                [_collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:dayModel.item inSection:dayModel.section] animated:YES scrollPosition:UICollectionViewScrollPositionBottom];
            }
        }
    }
    [_collectionView reloadData];
}

- (void)setMaxChooseNumber:(NSInteger)maxChooseNumber
{
    _maxChooseNumber = maxChooseNumber;
}



@end
